import api from '@/api'
import storage from '@/utils/storage'

const isExpire = (ctime, maxAge) => (new Date(ctime).getTime() + maxAge) <= Date.now()

const DEFAULT_MAX_AGE = 5 * 60 * 1000

const state = {}
const mutations = {}

const actions = {
  homePlaylist (params) {
    let homeTopPlaylist = storage.getItem('homeTopPlaylist')
    if (!homeTopPlaylist || // 结果未缓存
      isExpire(homeTopPlaylist.ctime, homeTopPlaylist.maxAge) // 缓存已失效
    ) {
      console.log('缓存失效，重新请求数据...')
      api.getTopPlaylist(params).then(res => {
        console.log(res.data)
        homeTopPlaylist = Object.assign(res.data, {
          ctime: Date.now(),
          maxAge: DEFAULT_MAX_AGE
        })
        // 写入缓存
        storage.setItem('homeTopPlaylist', homeTopPlaylist)
      })
    }
    return homeTopPlaylist
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
